package com.sjf.JavaNIO.file;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.stream.Stream;

/**
 * @author <huangtang>
 * @since 2022/4/16 9:51
 **/
public class FileDemo {

    //创建目录
    @Test
    public void create () {
        //createDirectory创建目录
        Path path = Paths.get ("D:\\atguigu\\test");
        try {
            Files.createDirectory (path);
        } catch (Exception e) {
            System.out.println (e.getMessage ());
        }
    }

    //拷贝文件
    @Test
    public void copy () {
        Path sourcePath = Paths.get ("D:\\atguigu\\01.txt");
        Path destinationPath = Paths.get ("D:\\atguigu\\test\\01.txt");

        try {
            Files.copy (sourcePath , destinationPath);
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }

    //删除文件
    @Test
    public void delete () {
        Path path = Paths.get ("D:\\atguigu\\test\\01.txt");

        try {
            Files.delete (path);
        } catch (IOException e) {
            e.printStackTrace ();
        }
        System.out.println ("文件删除成功");
    }

    //移动文件
    @Test
    public void move () {
        Path sourcePath = Paths.get ("D:\\atguigu\\0001.txt");
        Path destinationPath = Paths.get ("D:\\atguigu\\01.txt");

        try {
            Files.move (sourcePath , destinationPath);
        } catch (IOException e) {
            e.printStackTrace ();
        }
        System.out.println ("移动文件成功");
    }

    //遍历文件树查找文件
    @Test
    public void Tree () {
        Path path = Paths.get ("D:\\atguigu\\test");
        String fileToFind = File.separator + "01.txt";

        try {
            Files.walkFileTree (path , new SimpleFileVisitor<Path> () {
                @Override
                public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException {
                    String fileString = file.toAbsolutePath ().toString ();
                    System.out.println ("fileString:" + fileString);

                    if ( fileString.endsWith (fileToFind) ) {
                        //如果查找到文件就中止
                        System.out.println ("file found at path: " + file.toAbsolutePath ());
                        return FileVisitResult.TERMINATE;
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }

    public static void main ( String[] args ) {

    }

}
